﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WorkItemCollaborator
{
    /// <summary>
    /// Interaction logic for MyControl.xaml
    /// </summary>
    public partial class WICControl : UserControl
    {
        private User currentUser;
        private WicViewModel wicViewModel;
        public WICControl(WicViewModel wicViewModel)
        {
            this.DataContext = wicViewModel;
            InitializeComponent();
        }
        
        //public ObservableCollection<string> WorkItemFields { get; set; }
        
        private void WorkItemFieldsSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            WicViewModel wicViewModel = this.DataContext as WicViewModel;
            
            if (wicViewModel == null)
                return;

            var workItemFieldsSelection = (ComboBox) sender;
            var selectedField = (string)workItemFieldsSelection.SelectedItem;
            if (wicViewModel.WorkItem != null && wicViewModel.WorkItem.HistoryItems != null && wicViewModel.WorkItem.HistoryItems.Count > 0)
            {
                foreach (var historyItem in wicViewModel.WorkItem.HistoryItems)
                {
                    historyItem.IsVisible = true;
                }
                if (selectedField == "Any")
                {
                    wicViewModel.WorkItem.CurrentHistoryDisplayCount = wicViewModel.WorkItem.HistoryItems.Count;
                    return;
                }

                var selectedItems =  wicViewModel.WorkItem.HistoryItems.Where(
                    row => row.ChangedFields != null && !row.ChangedFields.Any(cf => cf.FieldName == selectedField));
                foreach (var selectedItem in selectedItems)
                {
                    selectedItem.IsVisible = false;
                }

                HistoryItem itemWithNoChangedField = wicViewModel.WorkItem.HistoryItems.FirstOrDefault(row => row.ChangedFields == null);
                if(itemWithNoChangedField != null)
                {
                    itemWithNoChangedField.IsVisible = false;
                }

                wicViewModel.WorkItem.CurrentHistoryDisplayCount = wicViewModel.WorkItem.HistoryItems.Where(row => row.IsVisible).Count();
            }
            this.HistoryListBox.Focus();
        }
       
    }
}